<!DOCTYPE html>


<html lang="en">
  

    <head>
      <meta charset="utf-8" />
        
      <meta
        name="viewport"
        content="width=device-width, initial-scale=1, maximum-scale=1"
      />
      <title>spring-boot记录sql探索 |  麦田麦穗</title>
  <meta name="generator" content="hexo-theme-ayer">
      
      <link rel="shortcut icon" href="/favicon.ico" />
       
<link rel="stylesheet" href="/dist/main.css">

      <link
        rel="stylesheet"
        href="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/css/remixicon.min.css"
      />
      
<link rel="stylesheet" href="/css/custom.css">
 
      <script src="https://cdn.jsdelivr.net/npm/pace-js@1.0.2/pace.min.js"></script>
       
 

      <link
        rel="stylesheet"
        href="https://cdn.jsdelivr.net/npm/@sweetalert2/theme-bulma@5.0.1/bulma.min.css"
      />
      <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.19/dist/sweetalert2.min.js"></script>

      <!-- mermaid -->
      
      <style>
        .swal2-styled.swal2-confirm {
          font-size: 1.6rem;
        }
      </style>
    </head>
  </html>
</html>


<body>
  <div id="app">
    
      
    <main class="content on">
      <section class="outer">
  <article
  id="post-java/spring-boot记录sql探索"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h1 class="article-title sea-center" style="border-left:0" itemprop="name">
  spring-boot记录sql探索
</h1>
 

      
    </header>
     
    <div class="article-meta">
      <a href="/2021/02/23/java/spring-boot%E8%AE%B0%E5%BD%95sql%E6%8E%A2%E7%B4%A2/" class="article-date">
  <time datetime="2021-02-23T11:28:29.000Z" itemprop="datePublished">2021-02-23</time>
</a>   
<div class="word_count">
    <span class="post-time">
        <span class="post-meta-item-icon">
            <i class="ri-quill-pen-line"></i>
            <span class="post-meta-item-text"> Word count:</span>
            <span class="post-count">1.5k</span>
        </span>
    </span>

    <span class="post-time">
        &nbsp; | &nbsp;
        <span class="post-meta-item-icon">
            <i class="ri-book-open-line"></i>
            <span class="post-meta-item-text"> Reading time≈</span>
            <span class="post-count">7 min</span>
        </span>
    </span>
</div>
 
    </div>
      
    <div class="tocbot"></div>




  
    <div class="article-entry" itemprop="articleBody">
       
  <blockquote>
<p>目标记录每次请求内的http、es、mysql耗时，本篇讨论mysql部分</p>
</blockquote>
<p>为什么说要探索，这不是很简单的事么？但是能满足以下几点么？</p>
<ul>
<li>能记录limit等参数</li>
<li>能将参数和sql写一起，能直接使用</li>
<li>能记录耗时</li>
<li>能计数累加,统计一次请求中sql执行的总数和总耗时</li>
</ul>
<span id="more"></span>

<h2 id="spring原生能力"><a href="#spring原生能力" class="headerlink" title="spring原生能力"></a>spring原生能力</h2><pre class="language-ini" data-language="ini"><code class="language-ini"><span class="token key attr-name">logging.level.org.hibernate.SQL</span><span class="token punctuation">=</span><span class="token value attr-value">debug</span>
<span class="token key attr-name">logging.level.org.hibernate.type.descriptor.sql.BasicBinder</span><span class="token punctuation">=</span><span class="token value attr-value">trace</span></code></pre>
<p>通过上面两条配置。</p>
<ul>
<li>✔️可以显示sql.</li>
<li>❌不能和参数一行显示</li>
<li>❌不能显示limit参数</li>
<li>❌不能计数和记录耗时</li>
</ul>
<pre class="language-none"><code class="language-none">2021-02-23 19:35:42.932 DEBUG 97586 --- [  restartedMain] org.hibernate.SQL                        : select admin0_.id as id1_0_, admin0_.create_time as create_t2_0_, admin0_.modify_time as modify_t3_0_, admin0_.email as email4_0_, admin0_.password as password5_0_, admin0_.status as status6_0_, admin0_.username as username7_0_ from admin admin0_ where admin0_.username&#x3D;?
2021-02-23 19:35:42.949 TRACE 97586 --- [  restartedMain] o.h.type.descriptor.sql.BasicBinder      : binding parameter [1] as [VARCHAR] - [root]</code></pre>

<h2 id="原生log-org-hibernate-EmptyInterceptor"><a href="#原生log-org-hibernate-EmptyInterceptor" class="headerlink" title="原生log+org.hibernate.EmptyInterceptor"></a>原生log+org.hibernate.EmptyInterceptor</h2><p><code>org.hibernate.EmptyInterceptor</code>提供钩子，hibernate本身提供entity的curd钩子。重写<code>EmptyInterceptor</code>方法，可以实现计数。但是<code>onPrepareStatement</code>方法只是装配sql前的事件，而且不是完整的sql。</p>
<ul>
<li>✔️ 可以显示sql</li>
<li>❌ 不能和参数一行显示</li>
<li>❌ 不能显示limit参数</li>
<li>✔️ 能计数</li>
<li>❌ 不能记录耗时</li>
</ul>
<pre class="language-ini" data-language="ini"><code class="language-ini"><span class="token key attr-name">spring.jpa.properties.hibernate.ejb.interceptor</span><span class="token punctuation">=</span><span class="token value attr-value">com.vison.itdoc.config.HibernateInterceptor</span></code></pre>

<pre class="language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">HibernateInterceptor</span> <span class="token keyword">extends</span> <span class="token class-name">EmptyInterceptor</span> <span class="token punctuation">&#123;</span>
    
    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> <span class="token keyword">boolean</span> <span class="token function">onLoad</span><span class="token punctuation">(</span><span class="token class-name">Object</span> entity<span class="token punctuation">,</span> <span class="token class-name">Serializable</span> id<span class="token punctuation">,</span> <span class="token class-name">Object</span><span class="token punctuation">[</span><span class="token punctuation">]</span> state<span class="token punctuation">,</span> <span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> propertyNames<span class="token punctuation">,</span> <span class="token class-name">Type</span><span class="token punctuation">[</span><span class="token punctuation">]</span> types<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
<span class="token comment">//        Log.info("onload...", entity)</span>
        <span class="token keyword">return</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
    
    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> <span class="token class-name">String</span> <span class="token function">onPrepareStatement</span><span class="token punctuation">(</span><span class="token class-name">String</span> string<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token comment">// count++</span>
        <span class="token keyword">return</span> INSTANCE<span class="token punctuation">.</span><span class="token function">onPrepareStatement</span><span class="token punctuation">(</span>string<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
    
    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">afterTransactionCompletion</span><span class="token punctuation">(</span><span class="token class-name">Transaction</span> t<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        INSTANCE<span class="token punctuation">.</span><span class="token function">afterTransactionCompletion</span><span class="token punctuation">(</span>t<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">Log</span><span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"after trans complete"</span><span class="token punctuation">,</span> t<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
    
<span class="token punctuation">&#125;</span></code></pre>

<h2 id="log4jdbc"><a href="#log4jdbc" class="headerlink" title="log4jdbc"></a>log4jdbc</h2><p>log4jdbc能很好的解决sql完整显示和记录耗时的问题</p>
<pre class="language-none"><code class="language-none">2021-02-23 19:59:13.709  INFO 97586 --- [nio-8081-exec-1] jdbc.sqltiming                           : select posts0_.id as id1_2_, posts0_.create_time as create_t2_2_, posts0_.modify_time as modify_t3_2_, 
posts0_.content as content4_2_, posts0_.title as title5_2_ from posts posts0_ where 1&#x3D;1 order 
by posts0_.id asc limit 10 ;
 &#123;executed in 1 msec&#125;</code></pre>

<p>还能够定义超过1定时间的执行sql记录为error类型。</p>
<pre class="language-xml" data-language="xml"><code class="language-xml"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>dependency</span><span class="token punctuation">></span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>groupId</span><span class="token punctuation">></span></span>com.googlecode.log4jdbc<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>groupId</span><span class="token punctuation">></span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>artifactId</span><span class="token punctuation">></span></span>log4jdbc<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>artifactId</span><span class="token punctuation">></span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>version</span><span class="token punctuation">></span></span>1.2<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>version</span><span class="token punctuation">></span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>scope</span><span class="token punctuation">></span></span>runtime<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>scope</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>dependency</span><span class="token punctuation">></span></span>
</code></pre>

<pre class="language-ini" data-language="ini"><code class="language-ini">spring.datasource.driver-class-name: net.sf.log4jdbc.DriverSpy
<span class="token comment">#使用log4jdbc后mysql的url</span>
<span class="token key attr-name">spring.datasource.url</span><span class="token punctuation">=</span><span class="token value attr-value">jdbc:log4jdbc:mysql://localhost:3306/xxxx?useUnicode=true&amp;characterEncoding=UTF-8</span>
<span class="token comment">#使用log4jdbc后oracle的url</span>
<span class="token comment">#spring.datasource.url: jdbc:log4jdbc:oracle:thin:@127.0.0.1:1521:orcl</span>
</code></pre>
<p>注意需要添加<code>spring.datasource.driver-class-name</code> 和更改 <code>spring.datasource.url</code> 将jdbc改为 jdbc:log4jdbc</p>
<p><em>log4jdbc.properties</em>可以定义更多配置</p>
<pre class="language-ini" data-language="ini"><code class="language-ini"><span class="token comment">#配置为需要记录的包或类匹配路径</span>
<span class="token comment">#log4jdbc.debug.stack.prefix=com.drp</span>
<span class="token comment">#log4jdbc加载的drivers (驱动名)</span>
<span class="token comment">#log4jdbc.drivers=oracle.jdbc.OracleDriver</span>
<span class="token key attr-name">log4jdbc.auto.load.popular.drivers</span><span class="token punctuation">=</span><span class="token value attr-value">true</span>
<span class="token comment">#在日志中显示warn警告</span>
<span class="token key attr-name">log4jdbc.statement.warn</span><span class="token punctuation">=</span><span class="token value attr-value">true</span>
<span class="token comment">#毫秒值.执行时间超过该值的SQL语句将被记录为warn级别.</span>
<span class="token key attr-name">log4jdbc.sqltiming.warn.threshold</span><span class="token punctuation">=</span><span class="token value attr-value">2000</span>
<span class="token comment">#毫秒值.执行时间超过该值的SQL语句将被记录为error级别.</span>
<span class="token key attr-name">log4jdbc.sqltiming.error.threshold</span><span class="token punctuation">=</span><span class="token value attr-value">3000</span>
<span class="token comment">#是把boolean记录为 'true'/'false' 还是 1/0. 默认设置为false,不启用,为了移植性.</span>
<span class="token comment">#log4jdbc.dump.booleanastruefalse=true</span>
<span class="token comment">#输出的sql,一行最大的字符数，默认90. 以后新版可能为0</span>
<span class="token comment">#log4jdbc.dump.sql.maxlinelength=90</span>
<span class="token comment">#如果在调试模式下转储，则转储整个堆栈跟踪  默认false</span>
<span class="token key attr-name">log4jdbc.dump.fulldebugstacktrace</span><span class="token punctuation">=</span><span class="token value attr-value">false</span>

<span class="token comment">#是否记录某些类型的语句，默认true</span>
<span class="token key attr-name">log4jdbc.dump.sql.select</span><span class="token punctuation">=</span><span class="token value attr-value">true</span>
<span class="token key attr-name">log4jdbc.dump.sql.insert</span><span class="token punctuation">=</span><span class="token value attr-value">true</span>
<span class="token key attr-name">log4jdbc.dump.sql.delete</span><span class="token punctuation">=</span><span class="token value attr-value">true</span>
<span class="token key attr-name">log4jdbc.dump.sql.update</span><span class="token punctuation">=</span><span class="token value attr-value">true</span>
<span class="token key attr-name">log4jdbc.dump.sql.create</span><span class="token punctuation">=</span><span class="token value attr-value">true</span>

<span class="token comment">#输出sql末尾处加入分号，默认false</span>
<span class="token key attr-name">log4jdbc.dump.sql.addsemicolon</span><span class="token punctuation">=</span><span class="token value attr-value">true</span>

<span class="token comment">#将此设置为false以不修剪已记录的SQL</span>
<span class="token key attr-name">log4jdbc.trim.sql</span><span class="token punctuation">=</span><span class="token value attr-value">true</span>
<span class="token comment">#将此设置为false不删除额外的空行</span>
<span class="token key attr-name">log4jdbc.trim.sql.extrablanklines</span><span class="token punctuation">=</span><span class="token value attr-value">true</span>

<span class="token comment">#log4jdbc.suppress.generated.keys.exception=false</span>

</code></pre>

<ul>
<li>✔️ 可以显示sql</li>
<li>✔️ 不能和参数一起显示</li>
<li>✔️ 不能显示limit参数</li>
<li>❌ 能计数</li>
<li>✔️  能记录单个sql耗时</li>
<li>❌ 不能统计总耗时</li>
</ul>
<p>不足的是，单纯log4jdbc并不能满足所有。理论上log4jdbc+org.hibernate.EmptyInterceptor可以满足需求了</p>
<h2 id="P6Spy"><a href="#P6Spy" class="headerlink" title="P6Spy"></a>P6Spy</h2><p>测试完毕，发现P6Spy目前最能满足需求：</p>
<ul>
<li>✔️ 可以显示sql</li>
<li>✔️ 不能和参数一起显示</li>
<li>✔️ 不能显示limit参数</li>
<li>✔️ 能计数</li>
<li>✔️ 不能记录耗时</li>
<li>✔️ 支持curd事件前后钩子，钩子参数返回sql和执行耗时及异常信息🚀</li>
</ul>
<pre class="language-xml" data-language="xml"><code class="language-xml"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>dependency</span><span class="token punctuation">></span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>groupId</span><span class="token punctuation">></span></span>p6spy<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>groupId</span><span class="token punctuation">></span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>artifactId</span><span class="token punctuation">></span></span>p6spy<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>artifactId</span><span class="token punctuation">></span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>version</span><span class="token punctuation">></span></span>3.9.1<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>version</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>dependency</span><span class="token punctuation">></span></span>
</code></pre>
<p>同<code>log4jdbc</code>需要改driver和url</p>
<pre class="language-ini" data-language="ini"><code class="language-ini"><span class="token key attr-name">spring.datasource.driver-class-name</span><span class="token punctuation">=</span><span class="token value attr-value">com.p6spy.engine.spy.P6SpyDriver</span>
<span class="token key attr-name">spring.datasource.url</span><span class="token punctuation">=</span><span class="token value attr-value">jdbc:p6spy:mysql://localhost:3306/test?useLegacyDatetimeCode=false&amp;serverTimezone=UTC</span></code></pre>

<p><em>psy.properties</em>可以定义更多配置</p>
<pre class="language-ini" data-language="ini"><code class="language-ini"><span class="token comment">#modulelist=com.p6spy.engine.spy.P6SpyFactory,com.p6spy.engine.logging.P6LogFactory,com.p6spy.engine.outage.P6OutageFactory</span>
<span class="token key attr-name">modulelist</span><span class="token punctuation">=</span><span class="token value attr-value">com.vison.itdoc.config.CustomeP6Factory,com.p6spy.engine.logging.P6LogFactory,com.p6spy.engine.outage.P6OutageFactory</span>
<span class="token comment">#moduelist很关键，我这里使用了自定义的Factory，因为我需要自定义event</span>
<span class="token key attr-name">appender</span><span class="token punctuation">=</span><span class="token value attr-value">com.p6spy.engine.spy.appender.Slf4JLogger</span>
<span class="token key attr-name">logMessageFormat</span><span class="token punctuation">=</span><span class="token value attr-value">com.p6spy.engine.spy.appender.CustomLineFormat</span>
<span class="token key attr-name">customLogMessageFormat</span><span class="token punctuation">=</span><span class="token value attr-value">%(executionTime) ms|%(category)|%(sql)</span>
<span class="token key attr-name">excludecategories</span><span class="token punctuation">=</span><span class="token value attr-value">result,resultset,info,debug</span></code></pre>

<p>正常使用默认配置就可以显示出sql和耗时信息</p>
<pre class="language-none"><code class="language-none">4 ms|statement|select admin0_.id as id1_0_, admin0_.create_time as create_t2_0_, admin0_.modify_time as modify_t3_0_, admin0_.email as email4_0_, admin0_.password as password5_0_, admin0_.status as status6_0_, admin0_.username as username7_0_ from admin admin0_ where admin0_.username&#x3D;&#39;root&#39;</code></pre>

<p>可以看到，耗时信息和实际参数</p>
<h3 id="自定义事件"><a href="#自定义事件" class="headerlink" title="自定义事件"></a>自定义事件</h3><p><code>modulelist=com.p6spy.engine.spy.P6SpyFactory</code>改成<code>自定义Factory</code></p>
<p>自定义Factory</p>
<pre class="language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">CustomeP6Factory</span> <span class="token keyword">implements</span> <span class="token class-name"><span class="token namespace">com<span class="token punctuation">.</span>p6spy<span class="token punctuation">.</span>engine<span class="token punctuation">.</span>spy<span class="token punctuation">.</span></span>P6Factory</span> <span class="token punctuation">&#123;</span>

    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> <span class="token class-name">P6LoadableOptions</span> <span class="token function">getOptions</span><span class="token punctuation">(</span><span class="token class-name">P6OptionsRepository</span> optionsRepository<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">P6SpyOptions</span><span class="token punctuation">(</span>optionsRepository<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> <span class="token class-name">JdbcEventListener</span> <span class="token function">getJdbcEventListener</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">P6spyListener</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">//使用自定义Listener</span>
    <span class="token punctuation">&#125;</span>

<span class="token punctuation">&#125;</span>
</code></pre>

<p>自定义事件</p>
<pre class="language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">P6spyListener</span> <span class="token keyword">extends</span> <span class="token class-name">JdbcEventListener</span> <span class="token punctuation">&#123;</span>

    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">onAfterExecuteQuery</span><span class="token punctuation">(</span><span class="token class-name">PreparedStatementInformation</span> statementInformation<span class="token punctuation">,</span> <span class="token keyword">long</span> timeElapsedNanos<span class="token punctuation">,</span> <span class="token class-name">SQLException</span> e<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">App</span><span class="token punctuation">.</span>sqlCount<span class="token punctuation">.</span><span class="token function">incrementAndGet</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">Log</span><span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"execute query..."</span><span class="token punctuation">,</span> statementInformation<span class="token punctuation">.</span><span class="token function">getSqlWithValues</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">onAfterExecuteUpdate</span><span class="token punctuation">(</span><span class="token class-name">PreparedStatementInformation</span> statementInformation<span class="token punctuation">,</span> <span class="token keyword">long</span> timeElapsedNanos<span class="token punctuation">,</span> <span class="token keyword">int</span> rowCount<span class="token punctuation">,</span> <span class="token class-name">SQLException</span> e<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">App</span><span class="token punctuation">.</span>sqlCount<span class="token punctuation">.</span><span class="token function">incrementAndGet</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">Log</span><span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"execute update.."</span><span class="token punctuation">,</span> statementInformation<span class="token punctuation">.</span><span class="token function">getSqlWithValues</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">onAfterExecute</span><span class="token punctuation">(</span><span class="token class-name">StatementInformation</span> statementInformation<span class="token punctuation">,</span> <span class="token keyword">long</span> timeElapsedNanos<span class="token punctuation">,</span> <span class="token class-name">String</span> sql<span class="token punctuation">,</span> <span class="token class-name">SQLException</span> e<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">Log</span><span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"execute.."</span><span class="token punctuation">,</span> statementInformation<span class="token punctuation">.</span><span class="token function">getSqlWithValues</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

<span class="token punctuation">&#125;</span></code></pre>

<p>可以看到，我在自定义事件中进行了sql计数.于是我可以在请求结束时打印每次请求的总sql执行次数。</p>
<pre class="language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">RequestInitInterceptor</span> <span class="token keyword">implements</span> <span class="token class-name">HandlerInterceptor</span> <span class="token punctuation">&#123;</span>

    <span class="token keyword">public</span> <span class="token class-name">RequestInitInterceptor</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> <span class="token keyword">boolean</span> <span class="token function">preHandle</span><span class="token punctuation">(</span><span class="token class-name">HttpServletRequest</span> request<span class="token punctuation">,</span> <span class="token class-name">HttpServletResponse</span> response<span class="token punctuation">,</span> <span class="token class-name">Object</span> handler<span class="token punctuation">)</span>
            <span class="token keyword">throws</span> <span class="token class-name">Exception</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">App</span><span class="token punctuation">.</span>_uniq_req_no <span class="token operator">=</span> UUID<span class="token punctuation">.</span><span class="token function">randomUUID</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">App</span><span class="token punctuation">.</span>sqlCount <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">AtomicInteger</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">Log</span><span class="token punctuation">.</span><span class="token function">setMsgTraceNo</span><span class="token punctuation">(</span><span class="token class-name">App</span><span class="token punctuation">.</span>_uniq_req_no<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">Log</span><span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"request start..."</span><span class="token punctuation">,</span> handler<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">afterCompletion</span><span class="token punctuation">(</span><span class="token class-name">HttpServletRequest</span> request<span class="token punctuation">,</span> <span class="token class-name">HttpServletResponse</span> response<span class="token punctuation">,</span> <span class="token class-name">Object</span> handler<span class="token punctuation">,</span> <span class="token class-name">Exception</span> ex<span class="token punctuation">)</span>
            <span class="token keyword">throws</span> <span class="token class-name">Exception</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">Log</span><span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">.</span><span class="token function">format</span><span class="token punctuation">(</span><span class="token string">"finish request sql执行次数:%s"</span><span class="token punctuation">,</span> <span class="token class-name">App</span><span class="token punctuation">.</span>sqlCount<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

<span class="token punctuation">&#125;</span></code></pre>

<p>由于事件参数还给出了<code>timeElapsedNanos</code>,最终我们还能统计出所有sql执行的耗时。这样一来我们就能看出一次请求内，最耗时的操作具体是什么。达到类似以下效果：</p>
<p><img src="https://vison-blog.oss-cn-beijing.aliyuncs.com/20210224141855.png" alt=""></p>
<h2 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h2><ul>
<li><a target="_blank" rel="noopener" href="http://knes1.github.io/blog/2015/2015-07-08-counting-queries-per-request-with-hibernate-and-spring.html">Counting Queries per Request with Hibernate and Spring</a></li>
<li><a target="_blank" rel="noopener" href="https://github.com/p6spy/p6spy/issues/362">register an event handler</a></li>
</ul>
 
      <!-- reward -->
      
      <div id="reword-out">
        <div id="reward-btn">
          Donate
        </div>
      </div>
      
    </div>
    

    <!-- copyright -->
    
    <div class="declare">
      <ul class="post-copyright">
        <li>
          <i class="ri-copyright-line"></i>
          <strong>Copyright： </strong>
          
          Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
          
        </li>
      </ul>
    </div>
    
    <footer class="article-footer">
       
<div class="share-btn">
      <span class="share-sns share-outer">
        <i class="ri-share-forward-line"></i>
        分享
      </span>
      <div class="share-wrap">
        <i class="arrow"></i>
        <div class="share-icons">
          
          <a class="weibo share-sns" href="javascript:;" data-type="weibo">
            <i class="ri-weibo-fill"></i>
          </a>
          <a class="weixin share-sns wxFab" href="javascript:;" data-type="weixin">
            <i class="ri-wechat-fill"></i>
          </a>
          <a class="qq share-sns" href="javascript:;" data-type="qq">
            <i class="ri-qq-fill"></i>
          </a>
          <a class="douban share-sns" href="javascript:;" data-type="douban">
            <i class="ri-douban-line"></i>
          </a>
          <!-- <a class="qzone share-sns" href="javascript:;" data-type="qzone">
            <i class="icon icon-qzone"></i>
          </a> -->
          
          <a class="facebook share-sns" href="javascript:;" data-type="facebook">
            <i class="ri-facebook-circle-fill"></i>
          </a>
          <a class="twitter share-sns" href="javascript:;" data-type="twitter">
            <i class="ri-twitter-fill"></i>
          </a>
          <a class="google share-sns" href="javascript:;" data-type="google">
            <i class="ri-google-fill"></i>
          </a>
        </div>
      </div>
</div>

<div class="wx-share-modal">
    <a class="modal-close" href="javascript:;"><i class="ri-close-circle-line"></i></a>
    <p>扫一扫，分享到微信</p>
    <div class="wx-qrcode">
      <img src="//api.qrserver.com/v1/create-qr-code/?size=150x150&data=http://visonforcoding.xyz/2021/02/23/java/spring-boot%E8%AE%B0%E5%BD%95sql%E6%8E%A2%E7%B4%A2/" alt="微信分享二维码">
    </div>
</div>

<div id="share-mask"></div>  
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/java/" rel="tag">java</a></li></ul>

    </footer>
  </div>

   
  <nav class="article-nav">
    
      <a href="/2021/03/03/%E7%BC%96%E5%8F%91%E7%BC%96%E7%A8%8B%E6%97%A5%E8%AE%B0-%E7%BA%BF%E7%A8%8B%E4%B8%8D%E5%AE%89%E5%85%A8%E7%9A%84%E5%8D%B1%E5%AE%B3/" class="article-nav-link">
        <strong class="article-nav-caption">上一篇</strong>
        <div class="article-nav-title">
          
            并发编程日记-线程不安全的危害
          
        </div>
      </a>
    
    
      <a href="/2021/02/22/java/spring-boot-vue%E7%9A%84%E5%89%8D%E5%90%8E%E7%AB%AF%E5%88%86%E7%A6%BB%E9%83%A8%E7%BD%B2/" class="article-nav-link">
        <strong class="article-nav-caption">下一篇</strong>
        <div class="article-nav-title">spring-boot+vue+supervisor+nginx的前后端分离部署</div>
      </a>
    
  </nav>

   
<!-- valine评论 -->
<div id="vcomments-box">
  <div id="vcomments"></div>
</div>
<script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/valine@1.4.14/dist/Valine.min.js"></script>
<script>
  new Valine({
    el: "#vcomments",
    app_id: "",
    app_key: "",
    path: window.location.pathname,
    avatar: "monsterid",
    placeholder: "给我的文章加点评论吧~",
    recordIP: true,
  });
  const infoEle = document.querySelector("#vcomments .info");
  if (infoEle && infoEle.childNodes && infoEle.childNodes.length > 0) {
    infoEle.childNodes.forEach(function (item) {
      item.parentNode.removeChild(item);
    });
  }
</script>
<style>
  #vcomments-box {
    padding: 5px 30px;
  }

  @media screen and (max-width: 800px) {
    #vcomments-box {
      padding: 5px 0px;
    }
  }

  #vcomments-box #vcomments {
    background-color: #fff;
  }

  .v .vlist .vcard .vh {
    padding-right: 20px;
  }

  .v .vlist .vcard {
    padding-left: 10px;
  }
</style>

 
   
     
</article>

</section>
      <footer class="footer">
  <div class="outer">
    <ul>
      <li>
        Copyrights &copy;
        2015-2021
        <i class="ri-heart-fill heart_icon"></i> vison
      </li>
    </ul>
    <ul>
      <li>
        
      </li>
    </ul>
    <ul>
      <li>
        
        
        <span>
  <span><i class="ri-user-3-fill"></i>Visitors:<span id="busuanzi_value_site_uv"></span></span>
  <span class="division">|</span>
  <span><i class="ri-eye-fill"></i>Views:<span id="busuanzi_value_page_pv"></span></span>
</span>
        
      </li>
    </ul>
    <ul>
      
    </ul>
    <ul>
      
    </ul>
    <ul>
      <li>
        <!-- cnzz统计 -->
        
        <script type="text/javascript" src='https://s9.cnzz.com/z_stat.php?id=1278069914&amp;web_id=1278069914'></script>
        
      </li>
    </ul>
  </div>
</footer>    
    </main>
    <div class="float_btns">
      <div class="totop" id="totop">
  <i class="ri-arrow-up-line"></i>
</div>

    </div>
    <aside class="sidebar on">
      <button class="navbar-toggle"></button>
<nav class="navbar">
  
  <div class="logo">
    <a href="/"><img src="/images/ayer-side.svg" alt="麦田麦穗"></a>
  </div>
  
  <ul class="nav nav-main">
    
    <li class="nav-item">
      <a class="nav-item-link" href="/">主页</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/archives">归档</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/categories">分类</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags">标签</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/%E6%97%85%E8%A1%8C/">旅行</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" target="_blank" rel="noopener" href="http://shenyu-vip.lofter.com">摄影</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/friends">友链</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/about">关于我</a>
    </li>
    
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      
      <a class="nav-item-link nav-item-search"  title="Search">
        <i class="ri-search-line"></i>
      </a>
      
      
      <a class="nav-item-link" target="_blank" href="/atom.xml" title="RSS Feed">
        <i class="ri-rss-line"></i>
      </a>
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
    </aside>
    <div id="mask"></div>

<!-- #reward -->
<div id="reward">
  <span class="close"><i class="ri-close-line"></i></span>
  <p class="reward-p"><i class="ri-cup-line"></i>请我喝杯咖啡吧~</p>
  <div class="reward-box">
    
    <div class="reward-item">
      <img class="reward-img" src="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/img/alipay.jpg">
      <span class="reward-type">支付宝</span>
    </div>
    
    
    <div class="reward-item">
      <img class="reward-img" src="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/img/wechat.jpg">
      <span class="reward-type">微信</span>
    </div>
    
  </div>
</div>
    
<script src="/js/jquery-3.6.0.min.js"></script>
 
<script src="/js/lazyload.min.js"></script>

<!-- Tocbot -->
 
<script src="/js/tocbot.min.js"></script>

<script>
  tocbot.init({
    tocSelector: ".tocbot",
    contentSelector: ".article-entry",
    headingSelector: "h1, h2, h3, h4, h5, h6",
    hasInnerContainers: true,
    scrollSmooth: true,
    scrollContainer: "main",
    positionFixedSelector: ".tocbot",
    positionFixedClass: "is-position-fixed",
    fixedSidebarOffset: "auto",
  });
</script>

<script src="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.js"></script>
<link
  rel="stylesheet"
  href="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.css"
/>
<script src="https://cdn.jsdelivr.net/npm/justifiedGallery@3.7.0/dist/js/jquery.justifiedGallery.min.js"></script>

<script src="/dist/main.js"></script>

<!-- ImageViewer -->
 <!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" style="display:none" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/default-skin/default-skin.min.css">
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe-ui-default.min.js"></script>

<script>
    function viewer_init() {
        let pswpElement = document.querySelectorAll('.pswp')[0];
        let $imgArr = document.querySelectorAll(('.article-entry img:not(.reward-img)'))

        $imgArr.forEach(($em, i) => {
            $em.onclick = () => {
                // slider展开状态
                // todo: 这样不好，后面改成状态
                if (document.querySelector('.left-col.show')) return
                let items = []
                $imgArr.forEach(($em2, i2) => {
                    let img = $em2.getAttribute('data-idx', i2)
                    let src = $em2.getAttribute('data-target') || $em2.getAttribute('src')
                    let title = $em2.getAttribute('alt')
                    // 获得原图尺寸
                    const image = new Image()
                    image.src = src
                    items.push({
                        src: src,
                        w: image.width || $em2.width,
                        h: image.height || $em2.height,
                        title: title
                    })
                })
                var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, {
                    index: parseInt(i)
                });
                gallery.init()
            }
        })
    }
    viewer_init()
</script> 
<!-- MathJax -->

<!-- Katex -->

<!-- busuanzi  -->
 
<script src="/js/busuanzi-2.3.pure.min.js"></script>
 
<!-- ClickLove -->

<!-- ClickBoom1 -->

<!-- ClickBoom2 -->

<!-- CodeCopy -->
 
<link rel="stylesheet" href="/css/clipboard.css">
 <script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<script>
  function wait(callback, seconds) {
    var timelag = null;
    timelag = window.setTimeout(callback, seconds);
  }
  !function (e, t, a) {
    var initCopyCode = function(){
      var copyHtml = '';
      copyHtml += '<button class="btn-copy" data-clipboard-snippet="">';
      copyHtml += '<i class="ri-file-copy-2-line"></i><span>COPY</span>';
      copyHtml += '</button>';
      $(".highlight .code pre").before(copyHtml);
      $(".article pre code").before(copyHtml);
      var clipboard = new ClipboardJS('.btn-copy', {
        target: function(trigger) {
          return trigger.nextElementSibling;
        }
      });
      clipboard.on('success', function(e) {
        let $btn = $(e.trigger);
        $btn.addClass('copied');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-checkbox-circle-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPIED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-checkbox-circle-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
      clipboard.on('error', function(e) {
        e.clearSelection();
        let $btn = $(e.trigger);
        $btn.addClass('copy-failed');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-time-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPY FAILED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-time-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
    }
    initCopyCode();
  }(window, document);
</script>
 
<!-- CanvasBackground -->

<script>
  if (window.mermaid) {
    mermaid.initialize({ theme: "forest" });
  }
</script>


    
    

  </div>
</body>

</html>